package com.harmonk.firstscene.ui.component

import android.annotation.SuppressLint
import android.app.Application
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.border
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuAnchorType
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.harmonk.firstscene.constants.CommonConstants
import com.harmonk.firstscene.constants.Utils
import com.harmonk.firstscene.db.entity.Person
import com.harmonk.firstscene.db.entity.Vehicle
import com.harmonk.firstscene.ui.model.PersonViewModel
import com.harmonk.firstscene.ui.model.PersonViewModelFactory
import com.harmonk.firstscene.ui.model.VehicleViewModel
import com.harmonk.firstscene.ui.model.VehicleViewModelFactory
import kotlinx.coroutines.launch

/**
 * 第二个Tab：显示这个TrafficEvent所属的Vehicle和Person
 */
@SuppressLint("RememberReturnType")
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun VehiclePersonTab(
    modifier: Modifier = Modifier,
    eventId: Long,
) {
    val vehicleViewModel: VehicleViewModel = viewModel(
        factory = VehicleViewModelFactory(
            LocalContext.current.applicationContext as Application
        )
    )
    val personViewModel: PersonViewModel = viewModel(
        factory = PersonViewModelFactory(
            LocalContext.current.applicationContext as Application
        )
    )
    val coroutineScope = rememberCoroutineScope()
    val vehicles by vehicleViewModel.vehicles.observeAsState(emptyList())
    val persons by personViewModel.persons.observeAsState(emptyList())
    var vehicleState by remember { mutableStateOf(Vehicle()) }
    var personState by remember { mutableStateOf(Person()) }
    val vehicleSheetState = rememberModalBottomSheetState(
        skipPartiallyExpanded = true
    )
    var showVehicleSheetState by remember { mutableStateOf(false) }
    val personSheetState = rememberModalBottomSheetState(
        skipPartiallyExpanded = true
    )
    var showPersonSheetState by remember { mutableStateOf(false) }
    var isIdentifierValid by remember { mutableStateOf(true) }

    LaunchedEffect(Unit) {
        vehicleViewModel.loadVehiclesByEventId(eventId)
        personViewModel.loadPersonsByEventId(eventId)
    }

    LaunchedEffect(showPersonSheetState) {
        if (personState.sfzId == "") {
            isIdentifierValid = true
        } else {
            isIdentifierValid = Utils.IdCardValidator.isValidIdCard(personState.sfzId)
        }
    }

    var showDeleteDialog by remember { mutableStateOf(false) }
    var itemToDelete by remember { mutableStateOf<Any?>(null) }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(8.dp) // 设置子组件间的垂直间距
        ) {
            if (vehicles.isEmpty()) {
                Text(
                    text = "暂无车辆信息",
                    modifier = Modifier.padding(vertical = 8.dp)
                )
            } else {
                vehicles.forEach { vehicle ->
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .border(
                                width = 1.dp,
                                color = MaterialTheme.colorScheme.outline,
                                shape = RoundedCornerShape(12.dp)
                            )
                            .padding(8.dp)
                            .combinedClickable(
                                onClick = {
                                    vehicleState = vehicle
                                    showVehicleSheetState = true
                                },
                                onLongClick = {
                                    itemToDelete = vehicle
                                    showDeleteDialog = true
                                }
                            ),
//                        shape = RoundedCornerShape(16.dp),
                        colors = CardDefaults.cardColors(
                            containerColor = Color.Transparent
                        )
                    ) {
                        // 车辆基本信息
                        Text(
                            text = "${vehicle.name} | ${vehicle.carNo} | ${CommonConstants.VEHICLE_TYPES[vehicle.type]}",
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.Bold
                        )

                        // 车辆备注
                        if (vehicle.memo.isNotEmpty()) {
                            Text(
                                text = vehicle.memo,
                                modifier = Modifier.padding(vertical = 6.dp),
                                style = MaterialTheme.typography.bodySmall
                            )
                        }

                        // 车上人员列表
                        val personsInVehicle =
                            persons.filter { it.vehicleId == vehicle.vehicleId }
                        if (personsInVehicle.isNotEmpty()) {
                            personsInVehicle.forEach { person ->
                                PersonItem(
                                    person = person,
                                    onClick = {
                                        personState = person
                                        showPersonSheetState = true
                                    },
                                    onLongClick = {
                                        itemToDelete = person
                                        showDeleteDialog = true
                                    }
                                )
                            }
                        }
                    }
                }
            }

            // 未分配车辆的人员列表
            val unassignedPersons = persons.filter { it.vehicleId == -1L }
            if (unassignedPersons.isNotEmpty()) {
                unassignedPersons.forEach { person ->
                    PersonItem(
                        person = person,
                        onClick = {
                            personState = person
                            showPersonSheetState = true
                        },
                        onLongClick = {
                            itemToDelete = person
                            showDeleteDialog = true
                        }
                    )
                }
            }
        }
        // 底部按钮
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            OutlinedButton(
                onClick = {
                    vehicleState = Vehicle(eventId = eventId)
                    showVehicleSheetState = true
                },
                modifier = Modifier.weight(1f)
            ) {
                Text("添加车辆")
            }

            OutlinedButton(
                onClick = {
                    personState = Person(eventId = eventId)
                    showPersonSheetState = true
                },
                modifier = Modifier
                    .padding(start = 8.dp)
                    .weight(1f)
            ) {
                Text("添加人员")
            }
        }
    }

    // 删除确认对话框
    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text("确认删除") },
            text = {
                Text(
                    if (itemToDelete is Vehicle)
                        "确定要删除这辆车及其所有相关信息吗？"
                    else
                        "确定要删除这个人员信息吗？"
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        itemToDelete?.let {
                            if (it is Vehicle) {
                                coroutineScope.launch {
                                    vehicleViewModel.deleteVehicle(it)
                                }
                            } else if (it is Person) {
                                coroutineScope.launch {
                                    personViewModel.deletePerson(it)
                                }
                            }
                        }
                        showDeleteDialog = false
                        itemToDelete = null
                    }
                ) {
                    Text("确认")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        showDeleteDialog = false
                        itemToDelete = null
                    }
                ) {
                    Text("取消")
                }
            }
        )
    }

    if (showVehicleSheetState) {
        ModalBottomSheet(
            onDismissRequest = { showVehicleSheetState = false },
            sheetState = vehicleSheetState,
        ) {
            // 车辆输入表单内容
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .imePadding() // 处理输入法填充
                    .navigationBarsPadding() // 处理导航栏填充
            ) {
                // 车辆名称输入框
                OutlinedTextField(
                    modifier = Modifier.fillMaxWidth(),
                    value = vehicleState.name,
                    onValueChange = {
                        vehicleState = vehicleState.copy(name = it)
                    },
                    label = { Text("代称") },
                    singleLine = true,
                )
                // 车牌号输入框
                OutlinedTextField(
                    modifier = Modifier.fillMaxWidth(),
                    value = vehicleState.carNo,
                    onValueChange = {
                        vehicleState = vehicleState.copy(carNo = it.uppercase())
                    },
                    label = { Text("号牌") },
                    singleLine = true,
                )
                // 车辆备注输入框
                OutlinedTextField(
                    modifier = Modifier.fillMaxWidth(),
                    value = vehicleState.memo,
                    onValueChange = {
                        vehicleState = vehicleState.copy(memo = it)
                    },
                    label = { Text("备注") },
                )
                // 选择车辆类型选择菜单
                var expanded by remember { mutableStateOf(false) }

                ExposedDropdownMenuBox(
                    expanded = expanded,
                    onExpandedChange = { expanded = it },
                    modifier = modifier
                        .fillMaxWidth()
                        .padding(top = 8.dp, bottom = 12.dp)
                ) {
                    OutlinedTextField(
                        // The `menuAnchor` modifier must be passed to the text field to handle
                        // expanding/collapsing the menu on click. A read-only text field has
                        // the anchor type `PrimaryNotEditable`.
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(MenuAnchorType.PrimaryNotEditable),
                        value = CommonConstants.VEHICLE_TYPES[vehicleState.type],
                        onValueChange = {},
                        readOnly = true,
                        singleLine = true,
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                    )
                    DropdownMenu(
                        expanded = expanded,
                        onDismissRequest = { expanded = false },
                        modifier = Modifier.exposedDropdownSize()
                    ) {
                        CommonConstants.VEHICLE_TYPES.forEachIndexed { index, type ->
                            DropdownMenuItem(
                                text = { Text(type) },
                                onClick = {
                                    vehicleState = vehicleState.copy(type = index)
                                    expanded = false
                                }
                            )
                        }
                    }
                }
                // 其他选项和按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    OutlinedButton(onClick = { showVehicleSheetState = false }) {
                        Text("取消")
                    }
                    OutlinedButton(
                        onClick = {
                            // 保存车辆
                            if (vehicleState.vehicleId == 0L) {
                                vehicleViewModel.insertVehicle(vehicleState)
                            } else {
                                vehicleViewModel.updateVehicle(vehicleState)
                            }
                            showVehicleSheetState = false
                        }
                    ) {
                        Text("保存")
                    }
                }
            }
        }
    }

    if (showPersonSheetState) {
        ModalBottomSheet(
            onDismissRequest = { showPersonSheetState = false },
            sheetState = personSheetState,
        ) {
            // 人员输入表单内容
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .imePadding() // 处理输入法填充
                    .navigationBarsPadding() // 处理导航栏填充
            ) {
                // 人员名称输入框
                OutlinedTextField(
                    modifier = Modifier.fillMaxWidth(),
                    value = personState.name,
                    onValueChange = {
                        personState = personState.copy(name = it)
                    },
                    label = { Text("姓名") },
                    singleLine = true,
                )

                // 人员手机号输入框
                OutlinedTextField(
                    modifier = Modifier.fillMaxWidth(),
                    value = if (personState.phone == 0L) "" else personState.phone.toString(),
                    onValueChange = {
                        personState = personState.copy(
                            phone = it.toLongOrNull() ?: 0
                        )
                    },
                    label = { Text("电话") },
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Phone
                    ),
                    singleLine = true,
                    suffix = {
                        Text("L:${personState.phone.toString().length}", style = MaterialTheme.typography.bodySmall)
                    }
                )
                // 人员身份证号码输入框
                OutlinedTextField(
                    modifier = Modifier.fillMaxWidth(),
                    value = personState.sfzId,
                    onValueChange = {
                        personState = personState.copy(sfzId = it.uppercase())
                        isIdentifierValid = if (it.length == 18) {
                            Utils.IdCardValidator.isValidIdCard(it)
                        } else {
                            false
                        }
                    },
                    label = { Text("证件号") },
                    singleLine = true,
                    isError = !isIdentifierValid,
                    suffix = {
                        Text("L:${personState.sfzId.length}", style = MaterialTheme.typography.bodySmall)
                    }
                )
                // 人员备注输入框
                OutlinedTextField(
                    modifier = Modifier.fillMaxWidth(),
                    value = personState.memo,
                    onValueChange = {
                        personState = personState.copy(memo = it)
                    },
                    label = { Text("备注") },
                )
                // 选择人员所属车辆
                var expandedBelongVehicle by remember { mutableStateOf(false) }
                var belongVehicleText by remember { mutableStateOf("无") }
//                 依据personState的vehicleId字段，更新belongVehicleText
                if (personState.vehicleId != -1L) {
                    val vehicle = vehicles.find { it.vehicleId == personState.vehicleId }
                    if (vehicle != null) {
                        belongVehicleText = vehicle.name
                    }
                } else {
                    belongVehicleText = "无"
                }

                ExposedDropdownMenuBox(
                    expanded = expandedBelongVehicle,
                    onExpandedChange = { expandedBelongVehicle = it },
                    modifier = modifier
                        .fillMaxWidth()
                        .padding(top = 8.dp, bottom = 8.dp)
                ) {
                    OutlinedTextField(
                        // The `menuAnchor` modifier must be passed to the text field to handle
                        // expanding/collapsing the menu on click. A read-only text field has
                        // the anchor type `PrimaryNotEditable`.
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(MenuAnchorType.PrimaryNotEditable),
                        value = "所属车辆：${belongVehicleText}",
                        onValueChange = {},
                        readOnly = true,
                        singleLine = true,
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expandedBelongVehicle) },
                    )
                    DropdownMenu(
                        expanded = expandedBelongVehicle,
                        onDismissRequest = { expandedBelongVehicle = false },
                        modifier = Modifier.exposedDropdownSize()
                    ) {
                        DropdownMenuItem(
                            text = { Text("无") },
                            onClick = {
                                personState = personState.copy(vehicleId = -1)
                                expandedBelongVehicle = false
                            }
                        )
                        if (vehicles.isNotEmpty()) {
                            vehicles.forEachIndexed { index, vehicle ->
                                DropdownMenuItem(
                                    text = { Text(vehicle.name) },
                                    onClick = {
                                        personState =
                                            personState.copy(vehicleId = vehicle.vehicleId)
                                        belongVehicleText = vehicle.name
                                        expandedBelongVehicle = false
                                    }
                                )
                            }
                        }
                    }
                }
                // 选择人员座位
                var expandedSeat by remember { mutableStateOf(false) }
                var selectedSeatIndex by remember { mutableIntStateOf(0) }
                ExposedDropdownMenuBox(
                    expanded = expandedSeat,
                    onExpandedChange = { expandedSeat = it },
                    modifier = modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp)
                ) {
                    OutlinedTextField(
                        // The `menuAnchor` modifier must be passed to the text field to handle
                        // expanding/collapsing the menu on click. A read-only text field has
                        // the anchor type `PrimaryNotEditable`.
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(MenuAnchorType.PrimaryNotEditable),
                        value = CommonConstants.PERSON_SEATS[selectedSeatIndex],
                        onValueChange = {},
                        readOnly = true,
                        singleLine = true,
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expandedSeat) },
                    )
                    DropdownMenu(
                        expanded = expandedSeat,
                        onDismissRequest = { expandedSeat = false },
                        modifier = Modifier.exposedDropdownSize()
                    ) {
                        CommonConstants.PERSON_SEATS.forEachIndexed { index, seat ->
                            DropdownMenuItem(
                                text = { Text(seat) },
                                onClick = {
                                    personState = personState.copy(seat = index)
                                    selectedSeatIndex = index
                                    expandedSeat = false
                                }
                            )
                        }
                    }
                }
                // 其他选项和按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    OutlinedButton(onClick = { showPersonSheetState = false }) {
                        Text("取消")
                    }
                    OutlinedButton(
                        onClick = {
                            // 保存人员
                            if (personState.personId == 0L) {
                                personViewModel.insertPerson(personState)
                            } else {
                                personViewModel.updatePerson(personState)
                            }
                            showPersonSheetState = false
                        }
                    ) {
                        Text("保存")
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PersonItem(
    person: Person,
    onClick: () -> Unit,
    onLongClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .combinedClickable(
                onClick = onClick,
                onLongClick = onLongClick
            ),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 座位信息
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 8.dp)
            ) {
                Text(
                    text = CommonConstants.PERSON_SEATS[person.seat],
                    fontSize = 12.sp,
                )
                Text(
                    text = person.name,
                    fontWeight = FontWeight.Bold
                )
            }

            // 人员详细信息
            Column(
                modifier = Modifier.weight(2f)
            ) {
                Text(
                    text = "电话：" + if (person.phone == 0L) "" else person.phone.toString(),
                    style = MaterialTheme.typography.bodySmall
                )
                Text(
                    text = "证件：" + person.sfzId,
                    style = MaterialTheme.typography.bodySmall
                )
                if (person.memo.isNotEmpty()) {
                    Text(
                        text = "备注：" + person.memo,
                        style = MaterialTheme.typography.bodySmall,
                    )
                }
            }
        }
    }
}